#include "constants.h";

XfMissionChapterExecute={
	private ["_chapter_succeeded"];
	diag_log "";
	diag_log "=========================================================================";
	diag_log "                             CHAPTER 1                                   ";
	diag_log "=========================================================================";
	diag_log "";
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Starting Chapter","_last_random_reinforcement","_random_reinf_diff","_reinforcement_power"];
	DM_Mission_ArtilleryVariables = [];
	DM_Mission_Chapter_CanRun = True;
	DM_Mission_Chapter_Runs = True;
	DM_Mission_Chapter_Success = 0;
	call XfMissionChapterSetup;
	_chapter_succeeded = false;
	if (!DM_Mission_Mission_CanRun) exitWith {diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Mission canceled!"];};
	
	// We need the castle infos to send paras to the right place :)
	_random_town = DM_Chapter_Location;
	_random_town_pos = _random_spot select XF_MAP_LOCATION_CENTER;
	_random_town_size = _random_spot select XF_MAP_LOCATION_SIZE;
	
	_file_found = false;
	_file_updated = false;
	_traitor_killed = false;
	_traitor_updated = false;
	_player_detected = false;

	_enemy_initial_counts = ([_random_town_pos,350,d_enemy_side] call XfMissionGetZoneSideCount) select 0;
	_unique_id = 0;
	_reinforcements = 10;
	_detected_time = time;

	_reinforcement_trigger = _enemy_initial_counts / 4;
	diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Entering the loop",[_enemy_initial_counts,_reinforcement_trigger], Time];
	while {DM_Mission_Chapter_CanRun AND DM_Mission_Mission_CanRun} do {
		sleep 10;
		_enemy_counts = ([_random_town_pos,350,d_enemy_side] call XfMissionGetZoneSideCount) select 0;
		_file_found = ["jip_file_found",false] call XNetGetJIP;
		_traitor_killed =["jip_traitor_killed",false] call XNetGetJIP;
		
		if (["jip_player_detected",false] call XNetGetJIP) then {_player_detected = true;};
		
		
		if (_file_found and !_file_updated) then {
			_file_updated = true;
			["FindTheFiles","", "","",[],"Succeeded"] call XfMissionTask;
		};
		
		if (_traitor_killed and !_traitor_updated) then {
			_traitor_updated = true;
			["KillTheTraitor","", "","",[],"Succeeded"] call XfMissionTask;
		};

		if (_player_detected and !_detected_updated) then {
			_detected_updated = true;
			"You are detected! Reinforcements will surely be called!" call XfMissionMessageToAll;
			_detected_time = time;
		};

		if (_file_found && _traitor_killed) then {
			_chapter_succeeded = true;
			DM_Mission_Chapter_CanRun = false;
			if ((([_random_town_pos,750,d_enemy_side] call XfMissionGetZoneSideCount) select 0) > 10) then {
				"We send an Air Support to cover you!" call XfMissionMessageToAll;
				for [{_i = 0},{_i<= 4},{_i=_i+1}] do {
					if !(DM_Mission_Mission_CanRun) exitWith{};
					_air_spawn = [(getPos FLAG_BASE),200] call XfGetRanPointCircleAir;
					if (!isnil "LHD_Center") then { _air_spawn = [(getPos LHD_Center),200] call XfGetRanPointCircleAir; };
					_unique_id = [d_own_side,[_random_town_pos,750],2,_air_spawn] call XfMissionCallAirSupport;
					sleep 6;
				};
			};
			if !(DM_Mission_Mission_CanRun) exitWith{};
			sleep 60;
		};
		// diag_log Format["(%1)[%2]: %3: %4: en:%5  kill:%6  det:%7  flee:%8",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Loop",_enemy_counts,_dealer_killed,_player_detected,_dealer_fleeing];
		If (DM_Mission_Chapter_CanRun AND _player_detected AND (_reinforcements > 0)) then {
			// If the player is detected and no reinforcement is on the way.. Then we send new troops in :)
			if ((_enemy_initial_counts - _enemy_counts) > _reinforcement_trigger) then {
				if (_unique_id == 0) then {
					// If the reinforcement function returns a value greater than 0, it means a reinforcement was created!
					_unique_id = [d_enemy_side,[_random_town_pos,_random_town_size],"PARA",DM_Mission_RandomReinforcement] call XfMissionCallReinforcement;
					if ((_unique_id) > 0) then {
						diag_log Format["(%1)[%2]: %3: %4: reinf:%5, diff:%6, ini:%7, vec:%8",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Sending reinforcement",_reinforcements,_enemy_diff,_enemy_initial_counts];
						_reinforcements = _reinforcements - 1;
						// hint "Reinforcement";
					};
				};
			} else {
				_unique_id = 0;
			};
		};
	};
	
	if (DM_Mission_Mission_CanRun) then {
		if (_chapter_succeeded) then {
			call XfMissionChapterSuccess;
		} else {
			call XfMissionChapterFailure;
		};
	} else {
		diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Mission canceled!"];
	};
	
	_players_found = true;
	While {DM_Mission_Mission_CanRun && (([_random_town_pos,400,d_enemy_side] call XfMissionGetZoneSideCount) select 0) > 3 && _players_found} do {
		sleep 5;
		_players_found = false;
		{
			if (([(getPos _x), _random_town_pos, 600] call XfPointInCircle) && isplayer _x) then { _players_found = true; };
		}foreach playableUnits;
	};
	// Just in case a reinforcement is already on the way.
	call XfMissionCancelReinforcement;
	call XfMissionChapterCleanUp;
	DM_Mission_Chapter_Runs = False;
};

XfMissionChapterSetup={
	private ["_random_town","_random_town_pos","_random_town_size","_troops_power","_troops_coeff","_grpSpecOps","_i"];
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Starting Initialization"];
	
	_random_town = [];
	_random_town_pos = [];
	_random_town_size = 200;
	_building = objNull;
	_i_tries = 30;
	while { count _random_town <= 0 && _i_tries > 0 } do {
		// Only big towns
		_random_town = [false] call XfMissionGetRandomTown;
		_random_town_pos = _random_town select XF_MAP_LOCATION_CENTER;
		_random_town_size = _random_town select XF_MAP_LOCATION_SIZE;
		_building = objNull;
		
		_objects = nearestObjects [_random_town_pos, ["Land_A_Office01","Land_A_MunicipalOffice","Land_A_Office02","Land_A_Office01_EP1","Land_ibrhotel","Land_block8_b","Land_block8_c","Land_block7","Land_block7_b","Land_block9","Land_block9_b"], _random_town_size / 1.5];
		while {isnull _building && (count _objects > 0)} do {
			_building = _objects call XfRandomArrayVal;
			_objects = _objects - [_building];
			_building_pos_intern = [_building,"INTERN",true] call XfMissionBuildingPosASL;
			_building_pos_hiding = [_building,"HIDE"] call XfMissionBuildingPosASL;
			if (d_mission_debug_messages) then { diag_log Format["(%1)[%2]: %3: %4: %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Testing building",[_building, count _objects, count _building_pos_intern, count _building_pos_hiding]]; };
			if  ((count _building_pos_intern) < 5 || (count _building_pos_hiding) < 2) then {
				_building = objNull;
			};
		};
		if (!isnull _building) exitWith {};
		_random_town = [];
		_i_tries = _i_tries - 1;
	};
	if ((count _random_town) <= 0) exitWith {"Could not pick a random site" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	if (isNull _building) exitWith {"Could not pick a random building" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	_random_town_name = _random_town select XF_MAP_LOCATION_DISPLAYNAME;
	DM_Chapter_Location = _random_town;
	DM_Chapter_Position = _random_town_pos;
	
	// This indicates where the mission takes place
	[_random_town_pos,_random_town_size,_random_town_name] call XfMissionCurrentPosition;
	// We search a spot to place the teleporter which is around the town on a road (to avoid mountains and forests)
	_teleporter = [_random_town_pos] call XfMissionRandomStartTeleporter;
	// If no spot found, we get back an empty position.
	if (count (_teleporter select 0) > 0) then {
		[false,["chapter1_start_position",(_teleporter select 0), "ICON", "ColorBlue", [1,1],"",(_teleporter select 1),"hd_start","",1]] call XfMissionMarker;
	};

	// The marker which indicates the buildings zone
	[false,["chapter1_random_town_zone", _random_town_pos, "ELLIPSE", "ColorRed", [_random_town_size,_random_town_size],"",0,"","BDiagonal",0.5]] call XfMissionMarker;
	[false,["chapter1_berezino_position",getPos _building, "ICON", "ColorRed", [1,1],"Intelligence Offices",0,"hd_objective","",0.6]] call XfMissionMarker;

	["jip_file_found",false] call XNetSetJIP;
	["jip_traitor_killed",false] call XNetSetJIP;

	_building_pos_hiding = [_building,"HIDE"] call XfMissionBuildingPosASL;
	if ((count _building_pos_hiding) <= 1) exitWith {"Could not pick enough building positions" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};

	// We create the traitor
	["jip_traitor_killed",false] call XNetSetJIP;
	_grp = [d_enemy_side] call x_creategroup;
	_pos_traitor = _building_pos_hiding call XfRandomArrayVal;
	_building_pos_hiding = _building_pos_hiding - [_pos_traitor];

	DM_VIP = ["RU_SchoolTeacher",_grp,_pos_traitor,"ASSASSINATE",["You killed the traitor","jip_traitor_killed"],"doStop this;"] call XfMissionCreateMissionUnit;
	DM_VIP = leader _grp;
	DM_VIP setPosASL _pos_traitor; 
	DM_VIP addWeapon "AKS_74_U";
	DM_VIP addMagazine "30Rnd_545x39_AK";
	DM_VIP addMagazine "30Rnd_545x39_AK";
	DM_VIP addMagazine "30Rnd_545x39_AK";
	DM_VIP addMagazine "smokeShell";
	DM_VIP addMagazine "smokeShell";
	[DM_VIP] call XfMissionStuckUnit;
	diag_log Format["(%1)[%2]: %3; %4: %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Traitor Position",_pos_traitor];
	
	_pos_files = _building_pos_hiding call XfRandomArrayVal;
	_pos_files set[2, (_pos_files select 2) + 0.4];
	_obj = ["EvMoscow",_pos_files,"PICKUP",["Informers Files","You found the documents!","jip_file_found","Take the files",True],Format["this allowDamage false;",_pos_files],"NONE"] call XfMissionCreateMissionObject;
	_obj setPosASL _pos_files;
	diag_log Format["(%1)[%2]: %3; %4: %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Files Position",_pos_files];
	
	// The trigger which will send reinforcement when the player is detected!
	["jip_player_detected",false] call XNetSetJIP;
	[_random_town_pos,750,d_own_side,d_enemy_side,"jip_player_detected"] call XfMissionSideDetected;
	
	// _officer_type = ["EAST",[XF_MISSION_CHAR_MILITARY_OFFICER]] call XfMissionGetCharacter;
	// _officer = [_officer_type,_grp,[_bunker_pos_hiding,20],"ARREST",["You caught the commander, congratulations!","Damn, you killed the commander....","jip_vip_found","jip_vip_alive"],"doStop this; this setRank ""COLONEL"";"] call XfMissionCreateMissionUnit;
	// if (isnull DM_VIP) exitWith {"Could not create the VIP" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};

	
	_grpSoldiers = [d_enemy_side,[(getPos _building),20],["chapter1_random_town_zone","noveh","aware","buildings","fortify"],floor(random(5))] call XfMissionCreateFootmenGroup;
	_grpSoldiers = [d_enemy_side,[(getPos _building),20],["chapter1_random_town_zone","noveh","aware","buildings","fortify"],floor(random(5))] call XfMissionCreateFootmenGroup;

	// This populates the larger zone
	// The last parameter indicates that only UAZ appear as vehicles
	[d_enemy_side,[_random_town_pos,750],true,0,0,1,0,true] call XfMissionPopulateLocation;
	
	["FindTheFiles","FindTheFiles", Format["We have been double crossed by one of our agents.<br />He sold precious files containing the names of our infiltrated agents in the country.<br />Thankfully, those files are encrypted and it will take some time before the enemy can decipher them. But we don't want to give them the chance to succeed.<br /><br />They took the files to their new Intelligence HQ in %1.<br />Go there, find the files and bring them back!",_random_town_name],"",[],"Created"] call XfMissionTask;
	["KillTheTraitor","Kill the Traitor", Format["We have been double crossed by one of our agents.<br />Not only did he stole the files, but he sold them to the enemy in exchange for their protection and dirty money.<br />You need to teach him... a last lesson.<br /><br />He is currently being questionned at the enemy Intelligence HQ in %1.<br />Make sure he doesn't escape!",_random_town_name],"",[],"Created"] call XfMissionTask;
	
	// This will create air support automatically if selected in the mission setup
	[d_enemy_side,[_random_town_pos,750],DM_Mission_AirSupport] call XfMissionCallAirSupport;

	DM_VIP setPosASL _pos_traitor; 
	
	_amount = round(random(12)) + 5;
	[[_random_town_pos,_random_town_size],d_enemy_side,_amount] call XfMissionCivilianSpawn;
};

XfMissionChapterSuccess={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSuccess","Starting"];
	"Congratulations! You saved our informers!" call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = 1;
};

XfMissionChapterFailure={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterFailure","Starting"];
	"You tried but failed... you'll do better next time." call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = -1;
};

// Self-explanatory
XfMissionChapterCleanUp={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterCleanUp","Starting"];
	// Giving an empty position places the teleporter back to the hangar, closing the hangar.
	[[],0] call XfMissionPlaceStartTeleporter;
	[] call XfMissionCleanMarkers;
	[] call XfMissionCleanTriggers;
	[] call XfMissionCleanTasks;
};

DM_Mission_Chapter_Compiled = true;